package counter;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisCounterExample2 {
    private static final String HOST = "localhost";
    private static final int PORT = 6379;
    private static final String KEY = "page_view";

    public static void main(String[] args) {
        // 创建线程池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);
        poolConfig.setMaxIdle(5);
        JedisPool jedisPool = new JedisPool(poolConfig, HOST, PORT);

        // 创建线程并启动
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new CounterTask(jedisPool));
            thread.start();
        }
    }

    static class CounterTask implements Runnable {
        private JedisPool jedisPool;

        public CounterTask(JedisPool jedisPool) {
            this.jedisPool = jedisPool;
        }

        @Override
        public void run() {
            // 从连接池中获取连接
            try (Jedis jedis = jedisPool.getResource()) {
                // 模拟访问网页
                for (int i = 0; i < 10; i++) {
                    // 计数器加1
                    long count = jedis.incr(KEY);
                    // 输出当前浏览量
                    System.out.println("Thread " + Thread.currentThread().getId() + " Page views: " + count);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}